// releasePage/pages/addExperience/addExperience.js
import throttle from '../../../utils/throttle.js';
import Http from '../../../utils/http.js';
const http = new Http();
const app = getApp();

Page({
    /**
     * 页面的初始数据
     */
    data: {
        // 刚进去时正在切换
        swipering: true,
        // 当前swiper-item
        current: 0,
        bgImg: [
            '../../images/experience/zhianyujing.png',
            '../../images/experience/zongjiao.png',
            '../../images/experience/suo.png',
            '../../images/experience/biaoqing.png',
            '../../images/experience/shandian.png',
            '../../images/experience/xingqubulas.png',
            '../../images/experience/feiji.png',
            '../../images/experience/tongyong.png',
            '../../images/experience/qita.png',
        ],
        // 经验分类数组
        experiencTypeArr: [],
        // 经验标题
        experienceTitle: '',
        textareaValue: '',
        sceneImageArr: [],
        // type '01'从经验首页或城市公告转移过来，'02'从城市经验
        type: '',
        // 经验类型名称
        experienceTypeName: '',
        // 经验类型id
        extypeid: '',
        // 国家
        country: '',
        // 城市
        city: '',
        // 关联位置
        associatedLocation: '',
        lat: '',
        lng: '',
        // 经验id
        experienceId: '',
        //操作弹框
        show: false,
        actions: [
            {
                name: '清除',
                color: '#333333',
                id: 2,
            },
            {
                name: '重新设置',
                color: '#333333',
                id: 1,
            },
        ],
        // 城市公告id
        noticeid: '',
        contentInfo: {}, //再次编辑内容
        detail: '', // 只有从经验详情页面编辑才会传'01'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            current: options.current == 1 ? 1 : 0,
            type: options.type,
            detail: options.detail,
        });
        if (options.id) {
            this.setData({
                experienceId: options.id,
            });
            this.getExperienceDetail(options.id);
        } else if (options.noticeid) {
            // 城市公告转经验
            this.setData({
                noticeid: options.noticeid,
            });
            this.getCityNoticeDetail(options.noticeid);
        } else {
            this.setData({
                experienceTypeName: options.typename,
                city: app.globalData.addressBack,
                country: app.globalData.countryBack,
                lat: app.globalData.cityLat,
                lng: app.globalData.cityLng,
                extypeid: options.extypeid,
            });
            // 需要把城市置空
            if (options.type === '01') {
                this.setData({
                    city: '',
                    country: '',
                    lat: '',
                    lng: '',
                });
            }
        }

        setTimeout(() => {
            this.setData({
                swipering: false,
            });
        }, 500);

        if (this.data.current == 0) {
            wx.setNavigationBarTitle({
                title: '录入经验',
            });
        } else {
            wx.setNavigationBarTitle({
                title: '录入经验/编辑',
            });
        }

        this.getExperienceTypeList();
    },

    swiperFinish() {
        if (!this.data.swipering) return;
        this.setData({
            swipering: false,
        });
    },

    onInput(e) {
        this.setData({
            textareaValue: e.detail.value,
        });
        app.numLimitTip(e.detail.value.length, 500);
    },

    bindKeyInput(e) {
        this.setData({
            experienceTitle: e.detail.value,
        });
        app.numLimitTip(e.detail.value.length, 30);
    },

    // 添加图片
    addImg(e) {
        const that = this;
        wx.chooseImage({
            count: 8 - that.data.sceneImageArr.length,
            success(res) {
                let imgLen =
                    that.data.sceneImageArr.length + res.tempFilePaths.length;
                if (imgLen > 8) {
                    wx.showModal({
                        content: '最多上传8张图片，请重新上传',
                        showCancel: false,
                    });
                    return;
                } else {
                    wx.showLoading({
                        title: '图片上传中',
                        mask: true,
                    });
                    const imgUploadResults = [];
                    let index = that.data.sceneImageArr.length;
                    for (let i = 0; i < res.tempFilePaths.length; i++) {
                        let imgUploadResult = app
                            .imgUpload(res.tempFilePaths[i])
                            .then((res) => {
                                let num = i + index;
                                that.data.sceneImageArr[num] = res;
                                that.setData({
                                    sceneImageArr: that.data.sceneImageArr,
                                });
                                console.log(that.data.sceneImageArr);
                            });
                        imgUploadResults.push(imgUploadResult);
                    }
                    Promise.all(imgUploadResults).then((values) => {
                        wx.hideLoading();
                    });
                }
            },
        });
    },
    // 删除图片
    deleteImg(e) {
        let index = e.currentTarget.dataset.index;
        console.log(index);
        this.data.sceneImageArr.splice(index, 1);
        this.setData({
            sceneImageArr: this.data.sceneImageArr,
        });
    },
    // 预览图片
    previewImage(e) {
        const current = e.target.dataset.src;
        wx.previewImage({
            current,
            urls: this.data.sceneImageArr,
        });
    },

    submit: throttle(
        function () {
            if (app.visitorPublish()) return; //游客发布限制
            if (!(this.data.experienceTitle && this.data.textareaValue)) return;
            let _that = this;
            let postData = _that.data.contentInfo;
            // wx.showModal({
            //     title: '确认提交？',
            //     content: '',
            //     success: function (res) {
            // if (res.confirm) {
            postData.title = _that.data.experienceTitle;
            postData.content = _that.data.textareaValue;
            postData.picurls = _that.data.sceneImageArr;
            postData.picurl = JSON.stringify(_that.data.sceneImageArr);
            postData.delflg = '02';
            postData.extypeid = _that.data.extypeid;
            postData.country = _that.data.country;
            postData.city = _that.data.city;
            postData.lat = _that.data.associatedLocation ? _that.data.lat : '';
            postData.lng = _that.data.associatedLocation ? _that.data.lng : '';
            postData.address = _that.data.associatedLocation;

            if (_that.data.experienceId) {
                postData.id = _that.data.experienceId;
                wx.request({
                    method: 'POST',
                    url:
                        app.globalData.rootPath +
                        'cjMap/editExperience?authId=' +
                        app.globalData.authId,
                    data: postData,
                    success(res) {
                        if (res.data.status === '0') {
                            app.globalData.expRefresh = true;
                            app.globalData.indexExpRefresh = true;
                            wx.removeStorageSync('refreshMapPointId'); //刷新地图标记点
                            let pages = getCurrentPages(); //当前页面栈

                            let prevPage = pages[pages.length - 2];
                            if (
                                prevPage &&
                                typeof prevPage.refresh == 'function'
                            ) {
                                // 如果是从经验详情页进入，编辑完后需要修改为新的id
                                if (_that.data.detail) {
                                    prevPage.setData(
                                        {
                                            id: res.data.data.id,
                                        },
                                        () => {
                                            prevPage.refresh();
                                        }
                                    );
                                } else {
                                    prevPage.refresh();
                                }
                            }

                            let prevPage2 = pages[pages.length - 3];
                            if (
                                prevPage2 &&
                                typeof prevPage2.refresh == 'function'
                            ) {
                                prevPage2.refresh(['count']);
                            }

                            let prevPage3 = pages[pages.length - 4];
                            if (
                                prevPage3 &&
                                typeof prevPage3.refresh == 'function'
                            ) {
                                prevPage3.refresh();
                            }

                            wx.showToast({
                                title: '提交成功',
                                icon: 'success',
                                duration: 1500,
                            });
                            setTimeout(function () {
                                wx.navigateBack({
                                    delta: 1,
                                });
                            }, 2000);
                        } else {
                            console.log('提交失败');
                        }
                    },
                });
            } else if (_that.data.noticeid) {
                _that.tranformCityNotice(postData);
            } else {
                wx.request({
                    method: 'POST',
                    url:
                        app.globalData.rootPath +
                        'cjMap/createExperience?authId=' +
                        app.globalData.authId,
                    data: postData,
                    success(res) {
                        if (res.data.status === '0') {
                            app.globalData.expRefresh = true;
                            app.globalData.indexExpRefresh = true;

                            let pages = getCurrentPages(); //当前页面栈

                            let prevPage = pages[pages.length - 2];
                            if (
                                prevPage &&
                                typeof prevPage.refresh == 'function'
                            ) {
                                prevPage.refresh();
                            }

                            let prevPage2 = pages[pages.length - 3];
                            if (
                                prevPage2 &&
                                typeof prevPage2.refresh == 'function'
                            ) {
                                prevPage2.refresh(['count']);
                            }

                            let prevPage3 = pages[pages.length - 4];
                            if (
                                prevPage3 &&
                                typeof prevPage3.refresh == 'function'
                            ) {
                                prevPage3.refresh();
                            }

                            wx.showToast({
                                title: '提交成功',
                                icon: 'success',
                                duration: 1500,
                            });
                            setTimeout(function () {
                                wx.navigateBack({
                                    delta: 1,
                                });
                            }, 2000);
                        } else {
                            console.log('提交失败');
                        }
                    },
                });
            }
            //         }
            //     },
            // });
        },
        5000,
        {
            trailing: false,
        }
    ),

    changeNav: throttle((e) => {
        let { nav } = e.currentTarget.dataset;
        console.log(nav);
        wx.navigateTo({
            url: `${nav}`,
        });
    }, 200),

    back() {
        this.setData(
            {
                current: 0,
            },
            () => {
                wx.setNavigationBarTitle({
                    title: '录入经验',
                });
            }
        );
    },

    openLocation: function (e) {
        var _that = this;
        if (
            _that.data.country &&
            _that.data.city &&
            _that.data.lat &&
            _that.data.lng
        ) {
            wx.chooseLocation({
                latitude: _that.data.lat,
                longitude: _that.data.lng,
                success: function (res) {
                    _that.setData({
                        associatedLocation: res.address || res.name,
                        lng: res.longitude,
                        lat: res.latitude,
                    });
                },
                fail: function (res) {
                    console.log(res);
                },
            });
        } else {
            wx.showToast({
                title: '请先选择城市',
                icon: 'none',
                duration: 2000,
            });
        }
    },

    //获取经验类别列表
    getExperienceTypeList() {
        let _that = this;
        let params = {};
        if (_that.data.type === '02') {
            params.country = _that.data.country || app.globalData.countryBack;
            params.city = _that.data.city || app.globalData.addressBack;
        }
        wx.request({
            url:
                app.globalData.rootPath +
                `cjMap/getExperienceTypeList?authId=${app.globalData.authId}`,
            method: 'GET',
            header: {
                'content-type': 'application/json',
            },
            data: params,
            success: function (res) {
                console.log(res);
                for (let i = 0; i < res.data.data.length; i++) {
                    let listItem = {
                        type: '',
                        count: 0,
                        iconPath: '',
                        id: '',
                    };
                    listItem.type = res.data.data[i].typename;
                    listItem.count = res.data.data[i].num;
                    listItem.id = res.data.data[i].id;
                    if (i > 6) {
                        if (i == res.data.data.length - 1) {
                            listItem.iconPath = _that.data.bgImg[8];
                        } else {
                            listItem.iconPath = _that.data.bgImg[7];
                        }
                    } else {
                        listItem.iconPath = _that.data.bgImg[i];
                    }
                    _that.data.experiencTypeArr.push(listItem);
                }
                _that.setData({
                    experiencTypeArr: _that.data.experiencTypeArr,
                });
            },
        });
    },

    // 阻止swiper手动滑动
    catchTouchMove: function (res) {
        return false;
    },

    // 切换类型
    changeType(e) {
        let { typename, extypeid, index } = e.currentTarget.dataset;

        // 针对当地经验
        if (this.data.type === '02') {
            let pages = getCurrentPages(); //当前页面栈
            let prevPage = pages[pages.length - 2]; //上一页面
            prevPage.setData({
                activeTypeName: typename,
                currentTabIndex: index + 1,
            });
        }

        this.setData(
            {
                experienceTypeName: typename,
                extypeid,
                current: 1,
            },
            () => {
                wx.setNavigationBarTitle({
                    title: '录入经验/编辑',
                });
            }
        );
    },

    // 查询经验详情
    getExperienceDetail(id) {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/getExperienceDetail',
            data: {
                authId: app.globalData.authId,
                id,
            },
            success: function (res) {
                let { experience } = res.data;

                // 针对swipering
                setTimeout(() => {
                    _that.setData({
                        experienceTypeName: experience.typename,
                        city: experience.city,
                        country: experience.country,
                        // 对于有城市但是没有具体位置的经验取默认城市经纬度
                        lat: experience.lat
                            ? experience.lat
                            : experience.citylat,
                        lng: experience.lng
                            ? experience.lng
                            : experience.citylng,
                        extypeid: experience.extypeid,
                        sceneImageArr: experience.picurls,
                        experienceTypeName: experience.typename,
                        associatedLocation: experience.address,
                        textareaValue: experience.content,
                        experienceTitle: experience.title || '',
                    });
                }, 600);
            },
        });
    },

    // 查询城市公告详情
    getCityNoticeDetail(id) {
        let data = {
            authId: app.globalData.authId,
            id: this.data.noticeid,
        };
        http.getRequest('cjMap/getCityNoticeDetail', data).then((res) => {
            let { experience } = res;
            this.setData({
                contentInfo: experience,
                city: experience.city,
                country: experience.country,
                // 对于有城市但是没有具体位置的经验取默认城市经纬度
                lat: experience.lat ? experience.lat : experience.citylat,
                lng: experience.lng ? experience.lng : experience.citylng,
                sceneImageArr: experience.picurl
                    ? JSON.parse(experience.picurl)
                    : [],
                associatedLocation: experience.address,
                textareaValue: experience.content,
                experienceTitle: experience.title || '',
            });
        });
    },

    // 城市公告转经验
    tranformCityNotice(postData) {
        http.postRequest(
            `cjMap/changeCityNoticeToOther?authId=${app.globalData.authId}&type=01&noticeid=${this.data.noticeid}`,
            postData
        ).then((res) => {
            app.globalData.expRefresh = true;
            app.globalData.indexExpRefresh = true;
            wx.removeStorageSync('refreshMapPointId'); //刷新地图标记点
            let pages = getCurrentPages(); //当前页面栈

            let prevPage = pages[pages.length - 2];
            if (prevPage && typeof prevPage.refresh == 'function') {
                prevPage.refresh();
            }
            wx.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 1500,
            });
            setTimeout(function () {
                wx.navigateBack({
                    delta: 1,
                });
            }, 2000);
        });
    },

    // 操作弹框
    openActionSheet() {
        this.setData({
            show: true,
        });
    },

    // 关闭操作弹框
    onCancel() {
        this.setData({
            show: false,
        });
    },

    // 选择操作
    onSelect(e) {
        if (e.detail.id == 1) {
            this.openLocation(e);
        } else if (e.detail.id == 2) {
            this.setData({
                associatedLocation: '',
            });
        }
        this.onCancel();
    },
});
